import { Player } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { Game } from "@sapi-game/main";
import { DimensionIds, EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { isReferee } from "@/func";
import { ScoreBoardDataBase } from "sapi-pro";
import { WereWolfSetting } from "@/werewolf/context";
import { WereWolfModule } from "@/werewolf/module";

export class WereWolfSettingComponent extends WereWolfModule.Component {
    private readonly db = new ScoreBoardDataBase("werewolf_setting");

    override onAttach(): void {
        this.subscribe(
            Game.events.buttonPush,
            (event) => {
                const player = event.source as Player;
                if (!isReferee(player)) {
                    player.sendMessage("你没有权限进行此操作");
                    return;
                }
                this.settingForm(player);
            },
            {
                loc: this.context.map.settingButtonLoc,
                dimensionId: DimensionIds.Overworld,
                sourceType: EntityTypeIds.Player,
            }
        );

        const setting = this.getSetting();
        // 初始化context设置
        this.context.config.restrictMode = setting.restrictMode;
        this.context.config.fullKill = setting.fullKill;
    }

    settingForm(player: Player) {
        const setting = this.getSetting();
        const form = new ModalFormData()
            .title("设置")
            .toggle("启用限制模式", {
                tooltip: "限制模式下玩家会受到严格限制，路人局建议开启",
                defaultValue: setting.restrictMode,
            })
            .dropdown("胜利条件", ["屠边", "屠城"], {
                tooltip: "屠边：村民和预言家存活即可\n屠城：所有好人阵营存活",
                defaultValueIndex: setting.fullKill ? 1 : 0,
            });

        form.show(player).then((result) => {
            if (result.canceled || !result.formValues) return;

            const restrictMode = result.formValues[0] as boolean;
            const fullKillIndex = result.formValues[1] as number;

            this.setSetting({ restrictMode, fullKill: fullKillIndex === 1 });
            player.sendMessage("§a设置已保存");
        });
    }

    getSetting(): WereWolfSetting {
        return {
            restrictMode: this.db.get("restrictMode") === 1,
            fullKill: this.db.get("fullKill") === 1,
        };
    }

    setSetting(setting: WereWolfSetting) {
        this.db.set("restrictMode", setting.restrictMode ? 1 : 0);
        this.db.set("fullKill", setting.fullKill ? 1 : 0);
        // 同步到context
        this.context.config.restrictMode = setting.restrictMode;
        this.context.config.fullKill = setting.fullKill;
    }
}
